package com.mhg.thread;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 测试wait方法
 */
public class MyThread extends Thread {
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
    StringBuilder value;
    public MyThread(StringBuilder value) {
        this.value = value;
    }

    public static synchronized void print(){

    }


    @Override
    public void run() {
        try {
            synchronized(value) {
                System.out.println("线程[" + Thread.currentThread().getName()+"]正在执行..."+"当前系统时间为：" + sdf.format(new Date()));
                if ((value.toString()).equals("123")) {
                    if ("线程1".equals(Thread.currentThread().getName())){
                        System.out.println(getName() + "开始等待;当前系统时间为：" + sdf.format(new Date()));
                        value.wait(5000);  // 注意这里不是说让value进行wait，而是让当前线程进行wait
                    }
                    if ("线程2".equals(Thread.currentThread().getName())){
                        value.notifyAll();  //唤醒一个线程
                    }
                } else {
                    value = value.append("2");
                    System.out.println("当前线程名：" + getName() + ";" + value );
                }
            }
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("当前系统时间为：" + sdf.format(new Date()));
    }

    /**
     * 入口程序
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        StringBuilder value = new StringBuilder("123");
        MyThread myThread1 = new MyThread(value);
        MyThread myThread2 = new MyThread(value);
        MyThread myThread3 = new MyThread(value);
        myThread1.setName("线程1");
        myThread2.setName("线程2");
        myThread3.setName("线程3");
        myThread1.start();
        myThread2.start();
        myThread3.start();
    }
}